package com.mofish.zbserver.common;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/common")
public class CommonAPI {
	@Resource
	private CommonService commonService;
	
	@GetMapping("/avatar/byname")
	public Result getU_avatarByU_name(@RequestParam("u_name") String u_name) {
		String u_avatar = commonService.getU_avatarByU_name(u_name);
		
		if (u_avatar==null || Constants.IMG_PATH_HOST.equals(u_avatar) || (Constants.IMG_PATH_HOST+"null").equals(u_avatar) ) {
			u_avatar = Constants.IMG_PATH_HOST + Constants.DEFAULT_AVATAR;
		}
		return Result.successData(u_avatar);
	}

    
    @GetMapping("/select/u_name")
    public Result selectU_nameByU_id(@RequestParam("u_id") String u_id) {
    	try {
			String u_name = commonService.selectU_nameByU_id(u_id);
			
			if (u_name==null) {
				return Result.fail(Result.ERR_CODE_BUSINESS, "无此用户！");
			}
			
			return Result.successData(u_name);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(Result.ERR_CODE_SYS, "查询失败！");
		}
    }
    
    @GetMapping("/select/u_name/bytoken")
    public Result selectU_nameByToken(@RequestHeader("Token") String token) {
    	try {
			String u_name = TokenUtils.getUserInfo(token, commonService).getU_name();
			return Result.successData(u_name);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(Result.ERR_CODE_BUSINESS, "Token错误！");
		}
    }
    
    @GetMapping("/check/login")
    public Result checkLogin(@RequestParam("Token") String token) {
    	try {
    		TokenUtils.verifyToken(token, commonService);
    	} catch (Exception e) {
    		e.printStackTrace();
    		return Result.fail(Result.ERR_CODE_BUSINESS, "登录已失效！");
    	}
    	
    	return Result.success("登录有效。", true);
    }
    
    @GetMapping("/check/u_name")
    public Result checkU_name(@RequestParam("u_name") String u_name) {
    	try {
    		Integer cnt = commonService.selectUserCountByU_name(u_name);
    		if (cnt==1) {
    			return Result.success();
    		} else {
    			return Result.fail(Result.ERR_CODE_BUSINESS, "无此用户！");
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		return Result.fail(Result.ERR_CODE_SYS, "系统错误！查询失败！");
    	}
    }
}
